import React from 'react';
import {Layout, Dropdown, Menu, Avatar} from 'antd';
import {withRouter} from 'react-router-dom';
import {connect} from 'react-redux';
import {
    MenuUnfoldOutlined,
    MenuFoldOutlined,
} from '@ant-design/icons';

const {Header} = Layout;

function TopHeader(props) {

    // const [collapsed, setcollapsed] = useState(false)

    // console.log(JSON.parse(localStorage.getItem('token')))
    const {username, role: {roleName}} = JSON.parse(localStorage.getItem('token'))

    // 下拉菜单的 menu
    const menu = (
        <Menu>
            <Menu.Item key='1'>{roleName}</Menu.Item>
            <Menu.Item key='2' danger onClick={() => {
                // 跳转到登录页面
                props.history.replace('/login')
                localStorage.clear()
            }}>退出</Menu.Item>
        </Menu>
    );

    return (
        <div className='noselect'>
            <Header className="site-layout-background" style={{padding: '0 16px'}}>
                {props.collapsed ? <MenuUnfoldOutlined onClick={() => {
                    // setcollapsed(!collapsed)
                    // 调用改变 collapsed 的 reducer
                    props.changeCollapsed()
                    // console.log(props)
                }
                }/> : <MenuFoldOutlined onClick={() => {
                    props.changeCollapsed()
                }
                }/>}

                <div style={{float: 'right'}}>
                    <span>欢迎您&nbsp;<span style={{color: 'orange'}}>{username}</span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    {/*  下拉菜单  */}
                    <Dropdown overlay={menu}>
                        <Avatar size="small" src="https://joeschmoe.io/api/v1/random"/>
                    </Dropdown>
                </div>
            </Header>
        </div>
    )
}

const mapStateToProps = (state) => {
    // console.log(state)
    return {
        collapsed:state.CollapsedReducer.collapsed
    }
}

const mapDispatchToProps = {
    changeCollapsed(){
        return {
            type: 'change-collapsed'
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(withRouter(TopHeader))